# -*- coding:utf-8 -*-
from socket import socket, AF_INET, SOCK_STREAM
import struct
import sys
import os

sys.path.append(os.path.join(sys.path[0], '../..'))
HEADER = [0xaa, 0x55]
from csi_data import CSI_Data
from csi_config import read_setting

PORT = int(read_setting('port'))
recvbuf = []
BUF_SIZE = 2048
client = socket(AF_INET, SOCK_STREAM, 0)
client.connect(('127.0.0.1', PORT))
totalcnt = 0
headeridx = -1


def find_header(buffer, header):
    try:
        return buffer.index(header)
    except ValueError:
        return -1


if __name__ == '__main__':
    while True:
        try:
            buf = client.recv(BUF_SIZE)
            if buf is None:
                client.close()
                sys.exit(-2)
            recvbuf.extend(buf)
            headeridx = find_header(recvbuf, HEADER)
            while headeridx != -1:
                tmpbuf = bytes(recvbuf[headeridx + len(HEADER):])
                i, = struct.unpack('>H', tmpbuf[:2])
                if i > len(tmpbuf):  # correct package check - 1
                    break
                else:
                    recvbuf = recvbuf[headeridx:]
                    package = recvbuf[:i]
                    recvbuf = recvbuf[i:]
                    tmppkg = recvbuf[4:-1]
                    lrc = recvbuf[-1]
                    lrct = 0
                    for i in range(len(tmppkg)):
                        lrct ^= tmppkg[i]
                    if lrct == lrc and tmppkg[0] == 187:  # correct package check - 2
                        dat = CSI_Data(tmppkg[1:])
                        print('num = %d rssia = %s' % (totalcnt, dat.rssi_a))
                headeridx = find_header(recvbuf, HEADER)
        except struct.error as e:
            print(e)
            client.close()
